﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Help;
using Model;
using System.Data;
using System.Collections;
using System.Reflection;

namespace BLLA
{
    public partial class View_Order_Form : BaseBLL<Model.View_Order_Form>, IBLL.IView_Order_FormBLL
    {
        ObjectSerialize os = new ObjectSerialize();
        DataResult result = new DataResult();

        /// <summary>
        /// 根据商户ID获取该商户的所有订单信息
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页面大小</param>
        /// <param name="StarTime">开始时间(""(全部)/yyyyMMdd)</param>
        /// <param name="EndTime">结束时间(""-全部/yyyyMMdd)</param>
        /// <param name="FormBY">订单状态(Order_FormControl_T.ConID(多选是用“,”分隔))</param>
        /// <param name="MerID">商户ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1:json;2:xml）</param>
        /// <returns></returns>
        public string GetOrder_Form(int pageIndex, int pageSize, string StarTime, string EndTime, string FormBY, string MerID, string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion
                List<Model.View_Order_Form> ls = new List<Model.View_Order_Form>();
               string tj = "";
                if (StarTime != "")
                {
                    var starTime = StarTime.Split('-');
                    var s = starTime[0] + starTime[1] + starTime[2];
                    tj += " AND FormTime >= '" + s + "000000'";
                }
                if (EndTime != "")
                {
                    var etarTime = EndTime.Split('-');
                    var e = etarTime[0] + etarTime[1] + etarTime[2];
                    tj += " AND FormTime <= '" + e + "235959'";
                }
                if (FormBY != "")
                {
                    string[] fbarr = FormBY.Split(new char[1]{','},StringSplitOptions.RemoveEmptyEntries);
                    tj += " AND FormBY = '" + fbarr[0] + "'  ";
                    for (int i = 1; i < fbarr.Length;i++ )
                    {
                        tj += " or FormBY = '" + fbarr[i] + "'  ";
                    }
               
                }
 
                ls = base.GetListBy("SELECT * FROM View_Order_Form where FormState=1 and FormMerID='" + MerID + "' " + tj + "  order by FormID desc");
                if (ls != null & ls.Count > 0)
                {
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.rows = ls.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                    result.total = ls.Count;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }
                return os.StringOfObject(result, RETID);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW(" 获取商品分类信息列表失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }


        #region 根据订单状态查询订单详细信息
        /// <summary>
        /// 根据订单状态查询订单详细信息
        /// </summary>
        /// <param name="FormID">订单ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1:json;2:xml）</param>
        /// <returns></returns>
        public string getOrderDetailByOrderID(int FormID, string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion
                Model.View_Order_Form vof = new Model.View_Order_Form();
                vof = base.DBSession.IView_Order_FormDAL.GetListBy("SELECT * FROM  View_Order_Form where FormState=1 and FormID=" + FormID).First();
                if (vof != null)
                {
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.rows = vof;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }

                return os.StringOfObject(result, RETID);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW(" 获取数据失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }
        #endregion 
        private static Model.View_Order_Form ToModel(DataRow row)
        {
            Model.View_Order_Form model = new Model.View_Order_Form();
            model.FormID = (int)row["FormID"];
            model.FormDishesID = (string)row["FormDishesID"];
            model.FormDisheName = (string)row["FormDisheName"];
            model.FormDishesNun = (string)row["FormDishesNun"];
            model.FormDishesMon = (string)row["FormDishesMon"];
            model.FornDishesInt = (string)row["FornDishesInt"];
            model.DelFormMon = (int)row["DelFormMon"];
            model.DelPackMon = (int)row["DelPackMon"];
            model.FormAllMon = (int)row["FormAllMon"];
            model.FormPreMon = (int)row["FormPreMon"];
            model.FormPayInt = (int)row["FormPayInt"];
            model.FormPreW = (int)row["FormPreW"];
            model.FormPayMon = (int)row["FormPayMon"];
            model.FormPayType = (int)row["FormPayType"];
            model.IsPay = (int)row["IsPay"];
            model.FormBY = (string)row["FormBY"];
            model.IsEva = (int)row["IsEva"];
            model.FormTime = (string)row["FormTime"];
            model.LastTime = (string)row["LastTime"];
            model.LastOper = (int)row["LastOper"];
            model.SenTime = (string)row["SenTime"];
            model.FormAddress = (string)row["FormAddress"];
            model.AccID = (int)row["AccID"];
            model.AccName = (string)row["AccName"];
            model.AccCall = (string)row["AccCall"];
            model.FormState = (int)row["FormState"];
            model.IntBZ = (string)row["IntBZ"];
            model.OperNum = row["OperNum"].ToString();
            model.ConText = (string)row["ConText"];
            model.FormMerID = (string)row["FormMerID"];
            model.MerName = (string)row["MerName"];
            model.Type = (string)row["Type"];
            return model;
        }

        /// <summary>
        /// 餐厅每月商户销量统计 --by lz
        /// </summary>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public string SalesCount(string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion

                #region 业务逻辑
                List<Model.Order_Mer_T> ls_mer = new List<Model.Order_Mer_T>();
                ls_mer = base.DBSession.IOrder_Mer_TDAL.GetListBy("select * from Order_Mer_T where MerState=1");
                if (ls_mer!=null & ls_mer.Count>0)
                {
                    List<M_SalesCount> retcount = new List<M_SalesCount>();
                    M_SalesCount m = new M_SalesCount();
                    string[] arr_name = new string[ls_mer.Count];
                    string[] arr_count = new string[ls_mer.Count];
                    for (int i = 0; i < ls_mer.Count; i++)
                    {
                        arr_name[i] = ls_mer[i].MerName;
                        string now = DateTime.Now.ToString("yyyyMMddHHmmss");//当前时间
                        DateTime dt = DateTime.Now;
                        string startMonth = dt.AddDays(1 - dt.Day).ToString("yyyyMMdd000000"); //本月月初
                        List<Model.View_Order_Form> ls_form = new List<Model.View_Order_Form>();
                        ls_form = base.GetListBy("select *  from  View_Order_Form  where MerName='"+ls_mer[i].MerName+"' and FormTime>'"+ startMonth + "' and FormTime<'"+ now + "'  and FormState=1");
                        int count=0 ;
                        for (int j = 0; j < ls_form.Count; j++)
                        {
                            
                            string[] arr =ls_form[j].FormDishesNun.Split(',');
                            for (int k = 0; k < arr.Length; k++)
                            {
                                count += int.Parse(arr[k]);
                            }
                        }
                        arr_count[i] = count.ToString();
                        m.name = arr_name;
                        m.count = arr_count;
                        
                    }
                    retcount.Add(m);
                    if (retcount != null & retcount.Count > 0)
                    {
                        result.BS = "1";
                        result.Msg = "查询成功";
                        result.rows = retcount;
                        result.total = retcount.Count;
                    }
                    else
                    {
                        result.BS = "0";
                        result.Msg = "查询不到数据";
                    }
                    
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }
                return os.StringOfObject(result, RETID);
                #endregion
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("获取餐厅商户月销量失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }

        public class M_SalesCount
        {
            public string[] name { get; set; }
            public string[] count { get; set; }
        }

        /// <summary>
        /// 每月热门菜品排名 --by lz
        /// </summary>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public string get_count(string YZM,int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion

                #region 业务逻辑
                List<Model.Order_Mer_T> ls_mer = new List<Model.Order_Mer_T>();
                ls_mer = base.DBSession.IOrder_Mer_TDAL.GetListBy("select * from Order_Mer_T where MerState=1 ");//

                if (ls_mer != null & ls_mer.Count > 0)
                {
                    List<list_count> ls = new List<list_count>();
                    List<list_count> ls_new = new List<list_count>();
                    
                    for (int i = 0; i < ls_mer.Count; i++)
                    {
                        string now = DateTime.Now.ToString("yyyyMMddHHmmss");//当前时间
                        DateTime dt = DateTime.Now;
                        string startMonth = dt.AddDays(1 - dt.Day).ToString("yyyyMMdd000000"); //本月月初
                        List<Model.View_Order_Form> ls_form = new List<Model.View_Order_Form>();
                        string sql = "select * from  View_Order_Form  where MerName='" + ls_mer[i].MerName + "' and FormTime>'" + startMonth + "' and FormTime<'" + now + "'  and FormState=1";
                        ls_form = base.GetListBy(sql);
                        for (int j = 0; j < ls_form.Count; j++)
                        {
                            list_count lc = new list_count();
                            lc.mername = ls_mer[i].MerName;
                            string[] arrdishename = ls_form[j].FormDisheName.Split(',');
                            string[] arrcount = ls_form[j].FormDishesNun.Split(',');
                            for (int k = 0; k < arrcount.Length; k++)
                            {
                                lc.dishesname = arrdishename[k];
                                lc.count = int.Parse(arrcount[k]);
                                ls.Add(lc);
                            }
                        }

                    }
                    DataTable dd = new DataTable();
                    DataTable dt_new = new DataTable();
                    dt_new.Columns.Add("mername", Type.GetType("System.String"));
                    dt_new.Columns.Add("dishesname", Type.GetType("System.String"));
                    dt_new.Columns.Add("count", Type.GetType("System.Int32"));
                    dd = ToDataTable(ls);
                    Log.Debug("每月菜品被订购次数总量", dd.Rows.Count.ToString());
                    List<string> ls_only = new List<string>();
                    for (int i = 0; i < dd.Rows.Count; i++)
                    {
                        only only = new only();
                        only.dishename=dd.Rows[i][1].ToString();

                        if (ls_only.Contains(only.dishename))
                        {
                            //已统计
                        }
                        else
                        {
                            ls_only.Add(only.dishename);
                            Log.Debug("统计菜品名称", only.dishename);
                            Log.Debug("菜品所属餐厅", dd.Rows[i][0].ToString());
                            DataRow[] dr = dd.Select("dishesname='" +only.dishename + "'");
                            DataRow dr_new = dd.NewRow();
                            int c=0;
                            for (int d = 0;  d< dr.Count(); d++)
                            {
                                c += int.Parse(dr[d][2].ToString());
                            }
                            dr_new["mername"] = dr[0][0].ToString();
                            dr_new["dishesname"] = dr[0][1].ToString();
                            dr_new["count"] = c;
                            Log.Debug("统计菜品数量：",c.ToString() );
                            dt_new.Rows.Add(dr_new.ItemArray);
                            Log.Debug("", "======================================================");
                        }
                    }
                    dt_new.DefaultView.Sort = "count DESC";
                    dt_new = dt_new.DefaultView.ToTable();
                    IList<list_count> retcount = ModelConvertHelper<list_count>.ConvertToModel(dt_new);
                    if (retcount != null & retcount.Count > 0)
                    {
                        result.BS = "1";
                        result.Msg = "查询成功";
                        result.rows = retcount.Take(5);
                        result.total = retcount.Take(5).Count();
                    }
                    else
                    {
                        result.BS = "0";
                        result.Msg = "查询不到数据";
                    }
                    Log.Debug("统计", dt_new.Rows.Count.ToString());
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }
                return os.StringOfObject(result, RETID);
                #endregion

            }
            catch (Exception ex)
            {
                 WriteLog.WriteW("获取热门商品失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }

        /// <summary>
        /// 统计菜品名单
        /// </summary>
        public class list_count
        {
            public string mername { get; set; }
            public string dishesname { get; set; }
            public int count { get; set; }
        }
        
        /// <summary>
        /// 唯一菜品标识
        /// </summary>
        public class only
        {
            public string dishename { get; set; }
        }

        /// <summary>
        /// List 转datatable by lz
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(IEnumerable<T> collection)
        {

            var props = typeof(T).GetProperties();

            var dt = new DataTable();

            dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());

            if (collection.Count() > 0)
            {

                for (int i = 0; i < collection.Count(); i++)
                {

                    ArrayList tempList = new ArrayList();

                    foreach (PropertyInfo pi in props)
                    {

                        object obj = pi.GetValue(collection.ElementAt(i), null);

                        tempList.Add(obj);

                    }

                    object[] array = tempList.ToArray();

                    dt.LoadDataRow(array, true);

                }

            }

            return dt;

        }

        /// <summary>    
        /// 反射---datatable转实体类 by lz
        /// </summary>    
        public class ModelConvertHelper<T> where T : new()
        {
            public static IList<T> ConvertToModel(DataTable dt)
            {
                // 定义集合    
                IList<T> ts = new List<T>();

                // 获得此模型的类型   
                Type type = typeof(T);
                string tempName = "";

                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    // 获得此模型的公共属性      
                    PropertyInfo[] propertys = t.GetType().GetProperties();
                    foreach (PropertyInfo pi in propertys)
                    {
                        tempName = pi.Name;  // 检查DataTable是否包含此列    

                        if (dt.Columns.Contains(tempName))
                        {
                            // 判断此属性是否有Setter      
                            if (!pi.CanWrite) continue;

                            object value = dr[tempName];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                    ts.Add(t);
                }
                return ts;
            }
        }   


    }

      
}
